const moment = require('moment');
class Dashboard {
    /**
     * 首页收益
     * @api {GET}         /            首页收益
     * @apiName           /dashboard
     * @apiGroup          Dashboard
     * @apiVersion 0.1.0
     * @apiSuccessExample Success-Response:
     * {
        "code": 0,
        "msg": "success",
        "data": {
            "member": 0,
            "earnings": 0,
            "user": [0],
            "money": [0]
        }
       }
     */
    async index(ctx) {
        const {
            db,
            Op,
            user: {
                User: {
                    role: { role }
                }
            }
        } = ctx;

        let total = { member: '', earnings: '', user: '', money: '' };

        // 表格数据
        const day = parseInt(moment().format('DD'));
        let user = { where: {} };
        let countUser = [];
        let countMoney = [];
        total.user = countUser;
        total.money = countMoney;
        if (role === 'admin') {
            // admin 能看全部
            let money = { where: {} };
            // 循环
            for (let i = 1; i <= day; i++) {
                // 本月新增用户
                user.where.createdAt = {
                    [Op.between]: [
                        moment()
                            .subtract(day - i, 'days')
                            .format('YYYY-MM-DD'),
                        moment()
                            .subtract(day - (i + 1), 'days')
                            .format('YYYY-MM-DD')
                    ]
                };
                // 本月收入
                money.where.createdAt = {
                    [Op.between]: [
                        moment()
                            .subtract(day - i, 'days')
                            .format('YYYY-MM-DD'),
                        moment()
                            .subtract(day - (i + 1), 'days')
                            .format('YYYY-MM-DD')
                    ]
                };
                let n = await db.User.count(user);
                let m = await db.Use.sum('amount', money);
                countUser.push(n);
                countMoney.push(m);
            }
        } else {
            let money = { where: { merchantId: ctx.user.User.id } };
            // 循环
            for (let i = 1; i <= day; i++) {
                // 本月新增用户
                user.where.createdAt = {
                    [Op.between]: [
                        moment()
                            .subtract(day - i, 'days')
                            .format('YYYY-MM-DD'),
                        moment()
                            .subtract(day - (i + 1), 'days')
                            .format('YYYY-MM-DD')
                    ]
                };
                // 本月收入
                money.where.createdAt = {
                    [Op.between]: [
                        moment()
                            .subtract(day - i, 'days')
                            .format('YYYY-MM-DD'),
                        moment()
                            .subtract(day - (i + 1), 'days')
                            .format('YYYY-MM-DD')
                    ]
                };
                let n = await db.User.count(user);
                let m = await db.Use.sum('amount', money);
                countUser.push(n);
                countMoney.push(m);
                console.log(n, m);
            }
        }
        ctx.success(total);
    }
    /**
     * 首页数据统计
     * @api {GET}         /              首页数据统计
     * @apiName           /dashboardInfo
     * @apiGroup          Dashboard
     * @apiVersion 0.1.0
     * @apiSuccessExample Success-Response:
     * {
        "code": 0,
        "msg": "success",
        "data": {
            "user": 0, //新增用户
            "earnings": 0, //收入
            "member": 0, //新增会员
            "washCar": 0 //今日洗车
        }
       }
     */
    async info(ctx) {
        const {
            db,
            Op,
            user: { User }
        } = ctx;

        let total = { user: 0, earnings: 0, member: 0, washCar: 0 };

        // 今日新增
        let user = {
            where: {
                createdAt: {
                    [Op.between]: [
                        moment()
                            .startOf('days')
                            .format('YYYY-MM-DD HH:mm:ss'),
                        moment()
                            .endOf('days')
                            .format('YYYY-MM-DD HH:mm:ss')
                    ]
                }
            }
        };
        total.user = await db.User.count(user);

        // 今日洗车收益
        let earnings = {
            where: {
                createdAt: {
                    [Op.between]: [
                        moment()
                            .startOf('days')
                            .format('YYYY-MM-DD HH:mm:ss'),
                        moment()
                            .endOf('days')
                            .format('YYYY-MM-DD HH:mm:ss')
                    ]
                },
                type: {
                    [Op.ne]: 1
                }
            }
        };

        if (User.role.role !== 'admin') {
            earnings.where.merchantId = User.id;
        }

        total.earnings = await db.Use.sum('amount', earnings);

        // 新增会员
        let member = {
            where: {
                createdAt: {
                    [Op.between]: [
                        moment()
                            .startOf('days')
                            .format('YYYY-MM-DD HH:mm:ss'),
                        moment()
                            .endOf('days')
                            .format('YYYY-MM-DD HH:mm:ss')
                    ]
                }
            }
        };
        total.member = await db.Buy.count(member);

        // 今日洗车
        let washCar = {
            where: {
                createdAt: {
                    [Op.between]: [
                        moment()
                            .startOf('days')
                            .format('YYYY-MM-DD HH:mm:ss'),
                        moment()
                            .endOf('days')
                            .format('YYYY-MM-DD HH:mm:ss')
                    ]
                },
                type: {
                    [Op.ne]: 1
                }
            }
        };

        if (User.role.role !== 'admin') {
            washCar.where.merchantId = User.id;
        }

        total.washCar = await db.Use.count(washCar);

        ctx.success(total);
    }
    /**
     * 会员卡办理and次卡办理详情筛选
     * @api {GET}         /                会员卡办理and次卡办理详情筛选
     * @apiName           /cardInfo
     * @apiGroup          Dashboard
     * @apiParam          {Int}            page            页数
     * @apiParam          {Int}            startTim        开始时间
     * @apiParam          {Int}            endTime         结束时间
     * @apiVersion 0.1.0
     * @apiSuccessExample Success-Response:
     * {
        "code": 0,
        "msg": "success",
        "data": {
            "count": 2,
            "rows": [
             {
                "id": 4,
                "userId": 5,
                "type": "50次，此卡，有效期一年",
                "price": "189.99",
                "status": false,
                "createdAt": "2019-06-05T09:16:59.000Z",
                "updatedAt": "2019-06-05T09:17:01.000Z",
                "userData": {
                    "id": 5,
                    "nickName": "大毛",
                    "phone": null
                }
                }
             ]
        }
       }
     */
    async cardInfo(ctx) {
        const {
            db,
            Op,
            request: {
                query: { page = 1, startTime, endTime }
            }
        } = ctx;

        if (!startTime || !endTime) {
            ctx.errors('参数错误');
            return;
        }

        let condition = {
            limit: 10,
            offset: (parseInt(page) - 1) * 10,
            where: {
                createdAt: {
                    [Op.between]: [startTime, endTime]
                }
            },
            include: {
                as: 'userData',
                attributes: ['id', 'nickName', 'phone', 'avatarUrl'],
                required: true,
                model: db.User
            }
        };

        let data = await db.Buy.findAndCountAll(condition);

        ctx.success(data);
    }
    /**
     * 今日洗车筛选
     * @api {GET}         /                今日洗车筛选
     * @apiName           /washInfo
     * @apiGroup          Dashboard
     * @apiParam          {Int}            page            页数
     * @apiParam          {Int}            startTim        开始时间
     * @apiParam          {Int}            endTime         结束时间
     * @apiVersion 0.1.0
     * @apiSuccessExample Success-Response:
     *{
        "code": 0,
        "msg": "success",
        "data": {
        "count": 6,
        "rows": [
            {
                "id": 41,
                "orderId": "156092574390404958372889611",
                "userId": 13,
                "merchantId": 10,
                "deviceId": "F52700B503D7A4",
                "address": "四川省成都市武侯区市振中驾校武侯训练训练场（东北门)",
                "amount": "3.80",
                "payment": "会员卡支付",
                "type": 3,
                "over": true,
                "status": false,
                "createdAt": "2019-06-19T06:29:04.000Z",
                "updatedAt": "2019-06-25T02:29:02.000Z",
                "userData": {
                    "id": 13,
                    "nickName": "四面是海",
                    "phone": null,
                    "avatarUrl": "https://wx.qlogo.cn/mmopen/vi_32/sbGvlxAG1T6urARxpVcxrHPTOhlWpPTH6rxl73F1nncsLsvl0JuuE3djbL9yAA81hc4A5CvyyxqXcEgV1hZ44A/132"
                }
            }
        ]
        }
     }
     */
    async washInfo(ctx) {
        const {
            db,
            Op,
            request: {
                query: { page = 1, startTime, endTime }
            },
            user: { User }
        } = ctx;

        if (!startTime || !endTime) {
            ctx.errors('参数错误');
            return;
        }

        let condition = {
            limit: 10,
            offset: (parseInt(page) - 1) * 10,
            where: {
                createdAt: {
                    [Op.between]: [startTime, endTime]
                },
                type: {
                    [Op.ne]: 1
                }
            },
            include: {
                as: 'userData',
                attributes: ['id', 'nickName', 'phone', 'avatarUrl'],
                required: true,
                model: db.User
            }
        };

        if (User.role.role !== 'admin') {
            condition.where.merchantId = User.id;
        }

        let data = await db.Use.findAndCountAll(condition);

        ctx.success(data);
    }
    /**
     * 今日设备收入筛选
     * @api {GET}         /                今日设备收入筛选
     * @apiName           /deviceInfo
     * @apiGroup          Dashboard
     * @apiParam          {Int}            page            页数
     * @apiParam          {Int}            startTim        开始时间
     * @apiParam          {Int}            endTime         结束时间
     * @apiVersion 0.1.0
     * @apiSuccessExample Success-Response:
     *{
        "code": 0,
        "msg": "success",
        "data": {
        "count": 1,
        "rows": [
            {
                "id": 14,
                "merchantId": 10,
                "deviceId": "F52700B503D7A4",
                "areaName": "四川省成都市武侯区华锦路100号顺行物流旁",
                "total": 7.6
            }
         ]
        }
     }
     */
    async deviceInfo(ctx) {
        const {
            db,
            Op,
            request: {
                query: { page = 1, startTime, endTime }
            },
            user: { User }
        } = ctx;

        let condition = {
            where: {
                createdAt: {
                    [Op.between]: [startTime, endTime]
                },
                type: {
                    [Op.ne]: 1
                }
            },
            include: {
                as: 'userData',
                attributes: ['id', 'nickName', 'phone', 'avatarUrl'],
                required: true,
                model: db.User
            }
        };

        let device;
        if (User.role.role === 'admin') {
            // 查询总设备
            device = await db.Drives.findAndCountAll({
                limit: 10,
                offset: (parseInt(page) - 1) * 10,
                where: { merchantId: { [Op.ne]: 0 } }
            });

            let rows = ctx.jsonArr(device.rows);

            for (let i = 0; i < rows.length; i++) {
                condition.where.deviceId = rows[i].deviceId;

                let sum = await db.Use.sum('amount', condition);

                rows[i].total = sum;
            }

            device.rows = rows;
        } else {
            // 查询总设备
            device = await db.Drives.findAndCountAll({
                limit: 10,
                offset: (parseInt(page) - 1) * 10,
                where: { merchantId: User.id }
            });

            let rows = ctx.jsonArr(device.rows);

            for (let i = 0; i < rows.length; i++) {
                condition.where.deviceId = rows[i].deviceId;

                condition.where.merchantId = User.id;

                let sum = await db.Use.sum('amount', condition);

                rows[i].total = sum;
            }

            device.rows = rows;
        }

        ctx.success(device);
    }
}
module.exports = new Dashboard();
